// qiLiuyun.js
import api from '../api/Channel.js'
export default {
	data() {
		return {

		};
	},
	methods: {
		showLoading(text, type,icon) {
			if (type == 'showLoading') {
				uni.showLoading({
					title: text,
					mask: true // 防止触摸穿透[7](@ref)
				});
			} else if(type == 'showToast') {
				uni.showToast({
					title:text,
					icon: icon,
				}) // 可选值：success、loading、noneduration: 1000 // 显示时长（单位：ms）;
			}
		},
		async Tokenqiniu(imga,getFileName) {
			this.imga = imga // 传入图片路径
			const uploadToken = await this.getQiniuToken()
			const fileName = await this.getFileName(getFileName)
			return await this.uploadToQiniu(uploadToken, fileName)
		},
		getQiniuToken() {
			return new Promise((resolve, reject) => {
				const token = uni.getStorageSync('token') || ''
				uni.request({
					url: api.ctrl + '/qiniu/token',
					header:{
						Authorization:'Bearer '+  token 
					},
					success(res) {
						if(res.data.errorCode == 'A0101'){
							uni.showToast({
								title:'请先登陆',
								icon: 'error',
							})
							return
						}
						resolve(res.data.data.uploadToken)
					},
					fail: reject
				})
			})
		},

		getFileName(getFileName) {
			return new Promise((resolve, reject) => {
				uni.request({
					url: api.Channel + '/file-name',
					data: {
						route:getFileName || 'commodity'
					},
					success(res) {
						if (res.data.code == 0) {
							resolve(res.data.data)
						} else {
							wx.showToast({
								title: '未知错误，请联系管理员',
								icon: 'error',
								duration: 1000
							})
							reject(new Error('获取文件名失败'))
						}
					},
					fail: reject
				})
			})
		},

		uploadToQiniu(uploadToken, fileNameqiniu) {
			return new Promise((resolve, reject) => {
				const houzui = this.getFileExtension(this.imga)
				uni.uploadFile({
					url: 'https://up-z2.qiniup.com',
					filePath: this.imga,
					name: 'file',
					formData: {
						token: uploadToken,
						key: `${fileNameqiniu}.${houzui}`
					},
					success: (uploadRes) => {
						const key = JSON.parse(uploadRes.data).key
						resolve(key)
					},
					fail: reject
				})
			})
		},

		getFileExtension(url) {
			console.log(url)
			const cleanUrl = url.split('?')[0]
			const lastDotIndex = cleanUrl.lastIndexOf('.')
			if (lastDotIndex === -1) return ''
			return cleanUrl.slice(lastDotIndex + 1)
		}
	}
}